#include "devicemanager.h"
#include <QDebug>
#include <QUuid>

DeviceManager::DeviceManager(QObject *parent)
    : QObject(parent)
{
    // 初始化客户端设备ID
    m_deviceId = QUuid::createUuid().toString(QUuid::WithoutBraces);
}

DeviceManager::~DeviceManager()
{
    // 清理所有设备对象
    qDeleteAll(m_devices);
    m_devices.clear();
}

void DeviceManager::addDevice(const QString &ipAddress, const QString &deviceId)
{
    if (m_devices.contains(ipAddress)) {
        return; // 设备已存在
    }
    
    Device *device = new Device(ipAddress, deviceId.isEmpty() ? m_deviceId : deviceId, this);
    
    // 连接设备信号
    connect(device, &Device::connectionStateChanged, 
            this, &DeviceManager::onDeviceConnectionStateChanged);
    connect(device, &Device::errorOccurred, 
            this, &DeviceManager::onDeviceError);
    connect(device, &Device::challengeReceived, 
            this, &DeviceManager::onDeviceChallengeReceived);
    connect(device, &Device::loginSuccess, 
            this, &DeviceManager::onDeviceLoginSuccess);
    connect(device, &Device::loginFailed, 
            this, &DeviceManager::onDeviceLoginFailed);
    connect(device, &Device::networkConfigReceived,
            this, &DeviceManager::onDeviceNetworkConfigReceived);
    connect(device, &Device::networkConfigSetResult,
            this, &DeviceManager::onDeviceNetworkConfigSetResult);
    
    // 连接固件升级相关信号槽
    connect(device, &Device::firmwareUploadProgress,
            this, &DeviceManager::onDeviceFirmwareUploadProgress);
    connect(device, &Device::firmwareUploadComplete,
            this, &DeviceManager::onDeviceFirmwareUploadComplete);
    connect(device, &Device::firmwareUpgradeStarted,
            this, &DeviceManager::onDeviceFirmwareUpgradeStarted);
    connect(device, &Device::firmwareUpgradeStatusReceived,
            this, &DeviceManager::onDeviceFirmwareUpgradeStatusReceived);
    connect(device, &Device::firmwareUpgradeError,
            this, &DeviceManager::onDeviceFirmwareUpgradeError);
    
    m_devices.insert(ipAddress, device);
    emit deviceAdded(ipAddress);
}

void DeviceManager::removeDevice(const QString &ipAddress)
{
    if (!m_devices.contains(ipAddress)) {
        return; // 设备不存在
    }
    
    Device *device = m_devices.take(ipAddress);
    delete device;
    
    emit deviceRemoved(ipAddress);
}

Device* DeviceManager::getDevice(const QString &ipAddress) const
{
    return m_devices.value(ipAddress, nullptr);
}

bool DeviceManager::hasDevice(const QString &ipAddress) const
{
    return m_devices.contains(ipAddress);
}

QList<Device*> DeviceManager::getAllDevices() const
{
    return m_devices.values();
}

void DeviceManager::connectToDevice(const QString &ipAddress)
{
    Device *device = getDevice(ipAddress);
    if (device) {
        device->connectToDevice();
    }
}

void DeviceManager::disconnectFromDevice(const QString &ipAddress)
{
    Device *device = getDevice(ipAddress);
    if (device) {
        device->disconnectFromDevice();
    }
}

bool DeviceManager::isConnected(const QString &ipAddress) const
{
    Device *device = getDevice(ipAddress);
    return device ? device->isConnected() : false;
}

void DeviceManager::requestChallenge(const QString &ipAddress, const QString &username)
{
    Device *device = getDevice(ipAddress);
    if (device) {
        device->requestChallenge(username);
    }
}

void DeviceManager::login(const QString &ipAddress, const QString &username, 
                         const QString &challenge, const QString &credential, 
                         bool rememberMe)
{
    Device *device = getDevice(ipAddress);
    if (device) {
        device->login(username, challenge, credential, rememberMe);
    }
}

void DeviceManager::getNetworkConfig(const QString &ipAddress)
{
    Device *device = getDevice(ipAddress);
    if (device) {
        device->getNetworkConfig();
    }
}

void DeviceManager::setNetworkConfig(const QString &ipAddress, const QString &interfaceName, 
                                    bool enable, const QString &mode, const QString &ipAddressParam, 
                                    const QString &netmask, const QString &gateway)
{
    Device *device = getDevice(ipAddress);
    if (device) {
        device->setNetworkConfig(interfaceName, enable, mode, ipAddressParam, netmask, gateway);
    }
}

void DeviceManager::uploadFirmware(const QString &ipAddress, int chunkIndex, int totalChunks, 
                                  const QByteArray &chunkData, const QString &fileName, 
                                  qint64 fileSize, const QString &version, const QString &md5)
{
    Device *device = getDevice(ipAddress);
    if (device) {
        device->uploadFirmware(chunkIndex, totalChunks, chunkData, fileName, fileSize, version, md5);
    }
}

void DeviceManager::startFirmwareUpgrade(const QString &ipAddress, const QString &version, bool force)
{
    Device *device = getDevice(ipAddress);
    if (device) {
        device->startFirmwareUpgrade(version, force);
    }
}

void DeviceManager::getFirmwareUpgradeStatus(const QString &ipAddress)
{
    Device *device = getDevice(ipAddress);
    if (device) {
        device->getFirmwareUpgradeStatus();
    }
}

// 设备信号转发槽函数实现
void DeviceManager::onDeviceConnectionStateChanged(const QString &ipAddress, bool connected)
{
    emit connectionStateChanged(ipAddress, connected);
}

void DeviceManager::onDeviceError(const QString &ipAddress, const QString &errorMessage)
{
    emit errorOccurred(ipAddress, errorMessage);
}

void DeviceManager::onDeviceChallengeReceived(const QString &ipAddress, const QString &challenge, int expiresIn)
{
    emit challengeReceived(ipAddress, challenge, expiresIn);
}

void DeviceManager::onDeviceLoginSuccess(const QString &ipAddress, const QString &accessToken, 
                                        const QString &refreshToken, const QJsonObject &userInfo)
{
    emit loginSuccess(ipAddress, accessToken, refreshToken, userInfo);
}

void DeviceManager::onDeviceLoginFailed(const QString &ipAddress, int errorCode, const QString &errorMessage)
{
    emit loginFailed(ipAddress, errorCode, errorMessage);
}

void DeviceManager::onDeviceNetworkConfigReceived(const QString &ipAddress, const QJsonObject &config)
{
    emit networkConfigReceived(ipAddress, config);
}

void DeviceManager::onDeviceNetworkConfigSetResult(const QString &ipAddress, bool success, const QString &message)
{
    emit networkConfigSetResult(ipAddress, success, message);
}

// 固件升级相关槽函数实现
void DeviceManager::onDeviceFirmwareUploadProgress(const QString &ipAddress, int progress)
{
    emit firmwareUploadProgress(ipAddress, progress);
}

void DeviceManager::onDeviceFirmwareUploadComplete(const QString &ipAddress)
{
    emit firmwareUploadComplete(ipAddress);
}

void DeviceManager::onDeviceFirmwareUpgradeStarted(const QString &ipAddress, const QString &upgradeId, 
                                                   const QString &status, int estimatedDuration)
{
    emit firmwareUpgradeStarted(ipAddress, upgradeId, status, estimatedDuration);
}

void DeviceManager::onDeviceFirmwareUpgradeStatusReceived(const QString &ipAddress, const QString &status, 
                                                         int progress, const QString &message)
{
    emit firmwareUpgradeStatusReceived(ipAddress, status, progress, message);
}

void DeviceManager::onDeviceFirmwareUpgradeError(const QString &ipAddress, const QString &errorMessage)
{
    emit firmwareUpgradeError(ipAddress, errorMessage);
}